<template>
  <div class="queryMenu">
    <div class="menu-item-con">
      <div class="con">
        <el-collapse v-model="activeNames" @change="handleChange" accordion>
          <div style="margin-bottom: 15px" v-for="(item,index) in collapseData" :key="index">
            <el-collapse-item :name="item.id">
              <template #title>
                <div class="left-title">
                  <img src="@/assets/imgs/file.png" alt="file" width="18px" height="16px">
                  <span class="pl5 pr5">{{ item.name }}</span>
                  <span v-if="index>0" title="删除" @click.stop="handleDel(item.id)"
                        class="iconfont icon-shanchu2 del"></span>
                </div>
              </template>
              <div class="collapse-content">
                <div class="queryPage">
                  <div class="left-container">
                    <div class="flex1">
                      <div class="queryPage">
                        <el-tabs v-model="tabActive" type="border-card" :stretch="true"
                                 @tab-click="tabChange(tabActive)">
                          <el-tab-pane :label="item1.nodeType" :name="item1.nodeType" v-for="item1 of nodeOptions"
                                       :key="item1.nodeType">
                            <Optics v-if="tabActive === item1.nodeType&&activeNames===item.id"
                                    :activeNames="activeNames"
                                    :ref="`option${item.id}`"
                                    :nodeType="item1.nodeType" :newForms="item.newForm"
                                    :collapseData="collapseData"
                                    @changeFormData="changeFormData"
                            />
                          </el-tab-pane>
                        </el-tabs>
                      </div>
                    </div>
                  </div>

                </div>
              </div>
            </el-collapse-item>
          </div>
        </el-collapse>
      </div>
      <div class="bottom-item">
        <div class="add-item f14 mb15" @click="addCollapse">
          <span class="color4E9EFF">+Added</span>&nbsp; a new transit prediction query condition
        </div>
        <span class="handleBtn" @click="trackSimulation">Orbital <br /> Simulation</span>
        <span class="handleBtn" @click="transitPrediction">Transit <br /> Forecast</span>
        <span class="handleBtn" @click="clearAll">Clear</span>
      </div>
    </div>
  </div>
</template>

<script>
import { format, addDays } from "date-fns";
import { getNodes } from "@/api/myData";
import Optics from "@/views/scene/gdHome/leftModes/Query/Optics.vue";
import { getStripsInfo } from "@/api";

export default {
  components: {
    Optics
  },
  provide() {
    return {
      showLeft: this.showLeft,
      activeNames: () => this.activeNames,
      setLocalData: this.setLocalData,
      loadFormData: this.loadFormData
    };
  },
  data() {
    return {
      activeNames: "1",
      tabMenu: [
        "Optics",
        "SAR",
        "Hyperspectral",
        "Other"
      ],
      loading: false,
      loadFormData: {
        geometry: "",
        groupVal: "Resolution",
        groupType: "Resolution",
        scenetime: [format(new Date(), "yyyy-MM-dd hh:mm:ss"), format(addDays(new Date(), 2), "yyyy-MM-dd hh:mm:ss")],
        province: "",
        uploadFiles: null,
        satellite: [],
        checkDataList: [],
        sateCheckList: []
      },
      nameIndex: 1,
      collapseData: [
        {
          id: "1",
          name: "Orbit prediction 1",
          nodeType: "Optical",
          newForm: {
            geometry: "",
            groupVal: "Resolution",
            groupType: "Resolution",
            scenetime: [format(new Date(), "yyyy-MM-dd hh:mm:ss"), format(addDays(new Date(), 2), "yyyy-MM-dd hh:mm:ss")],
            province: "",
            uploadFiles: null,
            satellite: [],
            checkDataList: [],
            sateCheckList: []
          }
        }
      ],
      menuVisible: true,
      showQueryPage: true,
      showLeft: true,


      tabActive: "Optical",
      nodeOptions: []
    };
  },

  inject: ["resultVisible"],
  watch: {
    resultVisible: {
      handler(val) {
        if (!val) {
          const res = JSON.parse(localStorage.getItem("collapseData"));
          if (res && res.length > 0) {
            this.collapseData = res;
          } else {
            localStorage.setItem("collapseData", JSON.stringify(this.collapseData));
          }
        }
      },
      deep: true,
      immediate: true
    },
    collapseData: {
      handler(val) {
        if (val) {
          localStorage.setItem("collapseData", JSON.stringify(val));
        }
      },
      deep: true,
      immediate: true
    }

  },
  computed: {
    searchData() {
      return this.$store.getters.getSearchData;
    }
  },
  async mounted() {
    const res = await getNodes();
    if (res) {
      this.nodeOptions = res;
    }
    this.queryVisible=true
    this.handleChange(this.activeNames);
  },
  methods: {
    changeFormData(data) {
      const matchedItem = this.collapseData.find(item => item.id === this.activeNames);
      matchedItem.newForm = data;
    },
    tabChange() {
      const matchedItem = this.collapseData.find(item => item.id === this.activeNames);
      if (matchedItem) {
        matchedItem.nodeType = this.tabActive;
        matchedItem.newForm.satellite = [];
        matchedItem.newForm.checkDataList = [];
        localStorage.setItem("collapseData", JSON.stringify(this.collapseData));
      }
    },
    search(val) {
      this.$emit("search", val);
    },
    handleChange(val) {
      if (val) {
        this.handleCleanDraw();
        this.activeNames = val;
        this.$nextTick(() => {
          const matchedItem = this.collapseData.find(item => item.id === this.activeNames);
          this.tabActive = matchedItem.nodeType;
        });
      }
    },
    generateRandomId() {
      let timestamp = Date.now().toString(); // 获取当前时间戳
      let randomNum = Math.random().toString().slice(2, 8); // 获取0.后面的6位随机数
      return timestamp + randomNum;
    },
    addCollapse() {
      this.nameIndex += 1;
      this.collapseData = JSON.parse(localStorage.getItem("collapseData"));
      this.collapseData.push({
        id: this.generateRandomId(),
        name: `Orbit prediction   ${this.nameIndex}`,
        newForm: {
          ...this.loadFormData
        },
        nodeType: "Optical"
      });
      this.activeNames = this.collapseData[this.collapseData.length - 1].id;
      this.tabActive = "Optical";
      this.handleChange(this.activeNames, true);
    },
    handleCleanDraw() {
      const collapseData = JSON.parse(localStorage.getItem("collapseData"));
      collapseData.forEach(item => {
        if (item && item.newForm && item.newForm.geometry) {
          const refName = `option${item.id}`;
          const ref = this.$refs[refName];
          if (ref && Array.isArray(ref) && ref.length > 0 && typeof ref[0].clearDrawPaint === "function") {
            ref[0].clearDrawPaint();
          }
        }
      });
    },
    handleDel(id) {
      const currentIndex = this.collapseData.findIndex(item => item.id === id);
      if (currentIndex > -1) {
        this.collapseData.splice(currentIndex, 1);
        this.handleCleanDraw();
      }

    },
    trackSimulation() {
      const matchedItem = this.collapseData.find(item => item.id === this.activeNames);
      this.$emit("trackSimulation", matchedItem);
    },
    clearAll() {
      const matchedItem = this.collapseData.find(item => item.id === this.activeNames);
      matchedItem.newForm = JSON.parse(sessionStorage.getItem("resetDataForm")).newForm;
      const refName = `option${matchedItem.id}`;
      const ref = this.$refs[refName];
      if (ref && Array.isArray(ref) && ref.length > 0 && typeof ref[0].clearDrawPaint === "function") {
        ref[0].clearDrawPaint();
        ref[0].getPage();
      }
      this.$emit("clearAll");
    },
    async transitPrediction() {
      const data = this.getQueryParams();
      // 验证参数
      if (!Array.isArray(data) || data.length === 0) {
        return;
      }
      this.$emit("transitPrediction", true, data);
    },
    getQueryParams() {
      const collapseData = JSON.parse(localStorage.getItem("collapseData")) || [];
      const filterData = [];
      for (let i = 0; i < collapseData.length; i++) {
        const item = collapseData[i];
        const newForms = item.newForm;
        if (newForms.satellite.length <= 0) {
          this.$message.warning(item.name + ": please select satellite source");
          return false; // 过滤掉这个数据项
        }
        if (newForms.geometry == "") {
          this.$message.warning(item.name + ": please configure the region or upload the shp range");
          return false; // 过滤掉这个数据项
        }
        filterData.push({
          boundaryWkt: newForms.geometry,
          startTime: newForms.scenetime[0],
          endTime: newForms.scenetime[1],
          paramGroupName: item.name,
          productId: item.id,
          satelliteIds: newForms.satellite
        });
      }

      if (filterData.length === 0 || filterData.length < collapseData.length) {
        return;
      }
      return filterData;
    }
  }
};
</script>

<style scoped lang="scss">
.queryMenu {
  height: 100%;
  width: 100%;
  .menu-item-con {
    height: 100%;
    width: 100%;
    position: relative;
    .con {
      height: calc(100% - 200px);
      overflow-y: auto;
      width: 95%;
      margin: 10px auto;
      padding: 0 10px 0 0;
    }

    .bottom-item {
      font-size: 14px;
      font-weight: 400;
      color: #4E9EFF;
      cursor: pointer;
      position: absolute;
      bottom: 20px;
      margin-left: -190px;
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      align-items: center;
      left: 50%;

      .add-item {
        width: 96%;
        height: 40px;
        border-radius: 4px;
        border: 1px solid #787878;
        padding: 0 2px;
        box-sizing: border-box;
        cursor: pointer;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #fff;
      }

      .handleBtn {
        width: 75px;
        height: 35px;
        padding: 5px;
        margin: 10px;
        display: flex;
        justify-content: center;
        align-items: center;
        text-align: center;
        background: #515663;
        color: #fff;
        border-radius: 4px;

        &:hover, &.active {
          background: #4E9EFF;
          color: #fff;
        }
      }
    }
  }

  :deep(.el-collapse) {
    border: none;
  }

  :deep(.el-collapse-item) {
    .left-title {
      height: 50px;
      background: url("~@/assets/imgs/title-bg.png") no-repeat;
      background-size: 100%;
      padding: 0 10px;
      width: 100%;
      box-sizing: border-box;

      .del {
        margin-left: 20px;
        opacity: 0;
      }

      &:hover {
        .del {
          opacity: 1;
        }
      }
    }

    &:last-child {
      margin-bottom: 0;
    }

    .el-collapse-item__header,
    .el-collapse-item__wrap {
      font-size: 16px;
      color: #fff;
      border-radius: 4px;

      // background: #303642 !important;
      background-color: transparent;
    }

    .el-collapse-item__header {
      height: auto;
      border: none;
    }

    .el-collapse-item__content {
      position: relative;
    }
  }

  .collapse-content {
    color: #fff;
    border: 1px solid #787878;
    padding: 0px;
    border-top: none;
    box-sizing: border-box;

    .queryPage {
      //height: 69vh;

      position: relative;
      //overflow: auto;

      ::v-deep .el-tabs--border-card {
        background: transparent !important;
      }

      .el-tabs {
        --el-tabs-header-height: 52px;
      }

      :deep(.el-tabs--card > .el-tabs__header .el-tabs__nav) {
        border: 0px solid rgba(255, 255, 255, 0.2);
      }

      :deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
        border-bottom: 0px solid rgba(255, 255, 255, 0.2);
        border-left: 0px solid rgba(255, 255, 255, 0.2);
        height: 52px;
        line-height: 52px;
      }

      :deep(.el-tabs__item.is-active) {
        color: #ffffff;
      }
    }
  }

  .sel {
    width: 140px;
    height: 40px;
    background: #34353B;
    border-radius: 4px;
    border: 1px solid #787878;

  }

  .check-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 45px;
    padding: 10px;
    line-height: 45px;

    span {
      display: inline-block;
      width: 260px;
    }
  }
}

.select-popper {
  margin-left: -6px;

  .el-select-dropdown {
    position: absolute;
    z-index: 1001;
    border: none;
    border-radius: 4px;
    background-color: #FFF;
    -webkit-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    margin: 5px 0;
  }

  .el-select-dropdown__empty {
    display: none;
  }

  .el-input__suffix {
    display: none;
  }


}

:deep(.el-tabs--border-card) {
  border: 0px solid rgba(255, 255, 255, 0.2);
}

:deep(.el-tabs--border-card > .el-tabs__header) {
  border-bottom: 0px solid rgba(255, 255, 255, 0.2);
}

:deep(.el-tabs--border-card > .el-tabs__header .el-tabs__item.is-active) {
  border-right-color: transparent;
  border-left-color: transparent;
}

:deep(.el-tabs--border-card > .el-tabs__header .el-tabs__item) {
  color: #bebebe;
  height: 52px;
  line-height: 52px;
}

.left-container {

  z-index: 3;
  height: 100%;
  background: #1f222a;
  //box-shadow: 2px 0px 4px 0px rgba(5, 11, 30, 0.4);
  width: 100%;
  transition: all 0.3s ease-out;

  display: flex;
  flex-direction: column;

  .flex1 {
    flex: 1;
    overflow: hidden;
  }


}


.queryPage {
  height: 100%;
  box-sizing: border-box;
  position: relative;

  .el-tabs {
    height: 100%;
    --el-tabs-header-height: 52px;

    :deep(.el-tabs__content) {
      height: calc(100% - 67px);
    }

    :deep(.el-tabs--card > .el-tabs__header .el-tabs__nav) {
      border: 0px solid rgba(255, 255, 255, 0.2);
    }

    :deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
      border-bottom: 0px solid rgba(255, 255, 255, 0.2);
      border-left: 0px solid rgba(255, 255, 255, 0.2);
    }

    :deep(.el-tabs__item.is-active) {
      color: #ffffff;
    }

  }
}

.queryPage {
  //height: 69vh;
  background: #1d1e1f;
  position: relative;
  //overflow: auto;

  .el-tabs--border-card {
    background: transparent !important;
  }

  .el-tabs {
    --el-tabs-header-height: 52px;
  }
}

:deep(.el-tabs--border-card) {
  border: 0px solid rgba(255, 255, 255, 0.2);
}

:deep(.el-tabs--border-card > .el-tabs__header) {
  border-bottom: 0px solid rgba(255, 255, 255, 0.2);
  background: transparent;
  height: 52px;
  line-height: 52px;
}

:deep(.el-tabs--border-card > .el-tabs__header .el-tabs__item.is-active) {
  border-right-color: transparent;
  background: #1d1e1f;

  border-left-color: transparent;
}

:deep(.el-tabs--border-card > .el-tabs__header .el-tabs__item) {
  color: #bebebe;
  //background: #1d1e1f;
  background: rgb(38, 39, 39);
}
</style>
